<?php

namespace common\db;

use Yii;
use yii\web\NotFoundHttpException;
use yii\behaviors\TimestampBehavior;

/**
 * ActiveRecord is the base class for classes representing relational data in terms of objects.
 *
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class MongoActiveRecord extends \yii\mongodb\ActiveRecord {

    use \common\traits\ModelErrors;

    /**
     * @return string[] the primary keys of the associated Mongo collection.
     */
    public static function primaryKey() {
        return ['id'];
    }

    /**
     * @inheritdoc
     */
    public function behaviors() {
        $timestampBehavior = [
            'class' => TimestampBehavior::className(),
        ];
        if (!$this->hasAttribute('created_at')) {
            $timestampBehavior['createdAtAttribute'] = false;
        }
        if (!$this->hasAttribute('updated_at')) {
            $timestampBehavior['updatedAtAttribute'] = false;
        }
        return [
            $timestampBehavior
        ];
    }

    /**
     * 加入记录软删除
     * @param boolean $hard 是否真实删除
     * {@inheritdoc}
     */
    public function delete($hard = false) {
        if ($hard === false && $this->hasAttribute('deleted_at')) {
            $this->deleted_at = time();
            return $this->save();
        }
        return parent::delete();
    }

    /**
     * 查询对象是否存在存在返回记录不存在创建
     * @params $condition
     * @return static
     */
    public static function findOrNew($condition) {
        $model = static::findOne($condition);
        if ($model === null) {
            $className = self::className();
            $model = new $className();
            if (is_array($condition)) {
                $model->setAttributes($condition);
            }
        }
        return $model;
    }

    /**
     * 查询对象是否存在存在返回记录不存在返回异常
     * @params $condition
     * @return static
     */
    public static function findOrFail($condition) {
        $model = static::findOne($condition);
        if ($model === null) {
            throw new NotFoundHttpException('未找到数据模型对应的记录！');
        }
        return $model;
    }

}
